# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
from chatroom.cache import get_cache
from django.db import transaction

# Create your models here.
class Room(models.Model):
    name = models.CharField('房间名', max_length=60, unique=True)

    def __unicode__(self):
        return self.name

    def get_members_count(self):
        key = 'memberCount:%d' % (self.id, )
        cache = get_cache()
        members = cache.get(key)
        return members if members != None else 0

    def get_messages_count(self):
        key = 'messageCount:%d' % (self.id, )
        cache = get_cache()
        messages = cache.get(key)
        if messages == None:
            messages = self.message_set.filter(status='normal').count()
            cache.setex(key, messages, 30)
        return messages

    def get_popular_messages(self, offset=0, count=20):
        key = 'greatComments:%d' % (self.id, )
        cache = get_cache()
        message_ids = cache.zrevrangebyscore(key, '+inf', '-inf', offset, count)
        messages = []
        for i in message_ids:
            messages.append(Message.objects.filter(id=i, status='normal').first())
        return messages


STATUS = (
    ('normal', '正常'),
    ('deleted', '删除'),
)
class Message(models.Model):
    room = models.ForeignKey('Room', on_delete=models.CASCADE)
    nickname = models.CharField('作者昵称', max_length=32)
    content = models.CharField('内容', max_length=1024) 
    likes = models.PositiveIntegerField('点赞数', default=0)
    status = models.CharField('状态', max_length=10, choices=STATUS, default='normal', db_index=True)
    create_time = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return self.nickname

    def update_likes(self):
        self.likes = Thumbsup.objects.filter(message=self).count()
        self.save()

    def like(self, ip):
        if Thumbsup.objects.filter(message=self, ip=ip).count() == 0:
            with transaction.atomic():
                Thumbsup.objects.create(message=self, ip=ip)
                self.update_likes()
                key = 'greatComments:%d' % (self.room.id, )
                cache = get_cache()
                cache.zadd(key, self.id, self.likes)

    def unlike(self, ip):
        thumbsups = Thumbsup.objects.filter(message=self, ip=ip).all()
        with transaction.atomic():
            for i in thumbsups:
                i.delete()
            self.update_likes()
            key = 'greatComments:%d' % (self.room.id, )
            cache = get_cache()
            cache.zadd(key, self.id, self.likes)

    def is_liked(self, ip):
        return Thumbsup.objects.filter(message=self, ip=ip).count() > 0

class Thumbsup(models.Model):
    message = models.ForeignKey('Message', on_delete=models.CASCADE, db_index=True)
    ip = models.CharField('IP', max_length=40, db_index=True)

